#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPU自动扩缩容系统启动文件
用于Gunicorn部署
"""

from flask import Flask, request, jsonify
import logging
import time
import threading
from typing import Dict, List

# 导入HAI优化相关模块
from api.hai_api import HAIAPI
from core.autoscaler import AutoScaler
from core.monitor import PerformanceMonitor

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# 初始化组件
hai_api = HAIAPI()
autoscaler = AutoScaler(hai_api)
monitor = PerformanceMonitor()

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'service': 'gpu-autoscaling',
        'port': 2000,
        'timestamp': time.time()
    })

@app.route('/api/v1/system/status', methods=['GET'])
def get_system_status():
    """获取系统状态"""
    try:
        status = {
            'autoscaler_status': autoscaler.get_status(),
            'hai_api_status': hai_api.get_status(),
            'monitor_status': monitor.get_status(),
            'timestamp': time.time()
        }
        
        return jsonify({
            'success': True,
            'data': status
        }), 200
        
    except Exception as e:
        logger.error(f"获取系统状态失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/instances', methods=['GET'])
def list_instances():
    """列出所有GPU实例"""
    try:
        instances = hai_api.list_instances()
        
        return jsonify({
            'success': True,
            'data': {
                'instances': instances,
                'total': len(instances),
                'timestamp': time.time()
            }
        }), 200
        
    except Exception as e:
        logger.error(f"列出实例失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/instances', methods=['POST'])
def create_instance():
    """创建GPU实例"""
    try:
        data = request.get_json()
        
        # 获取创建参数
        instance_type = data.get('instance_type', 'GPU.S.1')
        region = data.get('region', 'ap-guangzhou')
        
        result = hai_api.create_instance(instance_type, region)
        
        if result['success']:
            logger.info(f"GPU实例创建成功: {result['instance_id']}")
            return jsonify({
                'success': True,
                'data': result
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': result['error']
            }), 500
            
    except Exception as e:
        logger.error(f"创建实例失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/instances/<instance_id>', methods=['DELETE'])
def delete_instance(instance_id):
    """删除GPU实例"""
    try:
        result = hai_api.delete_instance(instance_id)
        
        if result['success']:
            logger.info(f"GPU实例删除成功: {instance_id}")
            return jsonify({
                'success': True,
                'data': result
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': result['error']
            }), 500
            
    except Exception as e:
        logger.error(f"删除实例失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/autoscaling/start', methods=['POST'])
def start_autoscaling():
    """启动自动扩缩容"""
    try:
        data = request.get_json() or {}
        
        # 获取扩缩容参数
        min_instances = data.get('min_instances', 1)
        max_instances = data.get('max_instances', 5)
        scale_up_threshold = data.get('scale_up_threshold', 80)
        scale_down_threshold = data.get('scale_down_threshold', 20)
        
        result = autoscaler.start_autoscaling(
            min_instances=min_instances,
            max_instances=max_instances,
            scale_up_threshold=scale_up_threshold,
            scale_down_threshold=scale_down_threshold
        )
        
        if result['success']:
            logger.info("自动扩缩容启动成功")
            return jsonify({
                'success': True,
                'data': result
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': result['error']
            }), 500
            
    except Exception as e:
        logger.error(f"启动自动扩缩容失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/autoscaling/stop', methods=['POST'])
def stop_autoscaling():
    """停止自动扩缩容"""
    try:
        result = autoscaler.stop_autoscaling()
        
        if result['success']:
            logger.info("自动扩缩容停止成功")
            return jsonify({
                'success': True,
                'data': result
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': result['error']
            }), 500
            
    except Exception as e:
        logger.error(f"停止自动扩缩容失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/autoscaling/status', methods=['GET'])
def get_autoscaling_status():
    """获取自动扩缩容状态"""
    try:
        status = autoscaler.get_status()
        
        return jsonify({
            'success': True,
            'data': status
        }), 200
        
    except Exception as e:
        logger.error(f"获取自动扩缩容状态失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/monitor/metrics', methods=['GET'])
def get_metrics():
    """获取监控指标"""
    try:
        metrics = monitor.get_metrics()
        
        return jsonify({
            'success': True,
            'data': metrics
        }), 200
        
    except Exception as e:
        logger.error(f"获取监控指标失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/v1/sessions/cancel', methods=['POST'])
def cancel_session_tasks():
    """取消会话的所有任务"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '请求数据为空'}), 400
        
        session_id = data.get('session_id')
        if not session_id:
            return jsonify({'error': '缺少会话ID'}), 400
        
        # 取消会话相关任务
        result = autoscaler.cancel_session_tasks(session_id)
        
        if result['success']:
            return jsonify({
                'success': True,
                'data': result
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': result['error']
            }), 500
            
    except Exception as e:
        logger.error(f"取消会话任务失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'API接口不存在'}), 404

@app.errorhandler(405)
def method_not_allowed(error):
    return jsonify({'error': 'HTTP方法不允许'}), 405

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'error': '服务器内部错误'}), 500

def start_background_tasks():
    """启动后台任务"""
    try:
        # 启动监控线程
        monitor_thread = threading.Thread(target=monitor.start_monitoring)
        monitor_thread.daemon = True
        monitor_thread.start()
        
        logger.info("后台监控任务已启动")
        
    except Exception as e:
        logger.error(f"启动后台任务失败: {str(e)}")

if __name__ == '__main__':
    logger.info("启动GPU自动扩缩容系统...")
    
    # 启动后台任务
    start_background_tasks()
    
    logger.info("GPU自动扩缩容系统启动完成，端口: 2000")
    logger.info("生产环境请使用: gunicorn -w 2 -b 127.0.0.1:2000 start:app")
    
    # 开发环境测试端口
    app.run(host='127.0.0.1', port=2000, debug=False)